import UIKit

class ImageLoader {
    static let shared = ImageLoader()
    
    private let cache = NSCache<NSURL, UIImage>()
    private let session: URLSession
    
    private init() {
        let config = URLSessionConfiguration.default
        config.requestCachePolicy = .returnCacheDataElseLoad
        config.urlCache = URLCache.shared
        session = URLSession(configuration: config)
    }
    
    func loadImage(from url: URL, placeholder: UIImage?, completion: @escaping (Result<UIImage, Error>) -> Void) {
        // 检查缓存
        if let cachedImage = cache.object(forKey: url as NSURL) {
            print("📦 使用缓存图片: \(url)")
            completion(.success(cachedImage))
            return
        }
        
        print("🌐 从网络加载图片: \(url)")
        
        let task = session.dataTask(with: url) { [weak self] data, response, error in
            if let error = error {
                completion(.failure(error))
                return
            }
            
            guard let data = data,
                  let image = UIImage(data: data) else {
                completion(.failure(ImageError.invalidData))
                return
            }
            
            // 缓存图片
            self?.cache.setObject(image, forKey: url as NSURL)
            
            completion(.success(image))
        }
        
        task.resume()
    }
    
    func clearCache() {
        cache.removeAllObjects()
    }
}

enum ImageError: Error {
    case invalidData
    
    var localizedDescription: String {
        switch self {
        case .invalidData:
            return "无法从数据创建图片"
        }
    }
} 
